import { post, apiPaths } from '../../utils/request.js'

Page({
  data: {
    projectId: null,
    action: null, // 添加action字段来区分是创建还是编辑
    project: {
      id: null,
      name: '',
      description: '',
      status: '进行中',
      statusClass: 'open',
      memberCount: 0,
      taskCount: 0,
      completedTaskCount: 0,
      members: []
    },
    projectTasks: [],
    workflowStatuses: [],
    latestMessage: '',
    // 添加成员相关数据
    showAddMemberModal: false,
    selectedMember: null,
    memberRole: '成员'
  },

  onLoad(options) {
    if (options.action === 'create') {
      // 创建项目模式
      this.setData({
        action: 'create',
        project: {
          id: null,
          name: '',
          description: '',
          status: '进行中',
          statusClass: 'open',
          memberCount: 0,
          taskCount: 0,
          completedTaskCount: 0,
          members: []
        }
      })
      wx.setNavigationBarTitle({
        title: '创建项目'
      })
    } else if (options.id) {
      // 编辑项目模式
      this.setData({
        projectId: options.id,
        action: 'edit'
      })
      // 调用接口获取项目详情
      this.loadProjectDetail(options.id)
      wx.setNavigationBarTitle({
        title: '项目详情'
      })
    }
  },

  loadProjectDetail(projectId) {
    // 调用获取项目详情接口
    console.log('Loading project detail for ID:', projectId);
    post(apiPaths.getProjectDetail, { id: projectId }).then(res => {
      console.log('Project detail response:', res);
      if (res.code === 200) {
        const data = res.data
        const project = {
          id: data.project.id,
          name: data.project.name,
          description: data.project.description,
          status: data.project.status,
          statusClass: data.project.status === '进行中' ? 'open' : 'archived',
          memberCount: data.members.length,
          taskCount: data.taskStats.total,
          completedTaskCount: data.taskStats.completed,
          members: data.members
        }
        
        // 处理任务数据
        const tasks = (data.tasks || []).map(task => {
          return {
            id: task.id,
            title: task.title,
            status: task.status,
            statusClass: this.getStatusClass(task.status),
            priority: task.priority,
            priorityClass: this.getPriorityClass(task.priority),
            assignee: task.assignee_name
          }
        })
        
        // 设置工作流状态
        const workflowStatuses = data.workflows || []
        
        this.setData({
          project: project,
          projectTasks: tasks,
          workflowStatuses: workflowStatuses
        })
      } else {
        wx.showToast({
          title: res.message || '获取项目详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      console.error('Project detail error:', err);
      wx.showToast({
        title: err.message || '获取项目详情失败',
        icon: 'none'
      })
    })
  },
  
  getStatusClass(status) {
    switch (status) {
      case '已完成':
        return 'completed'
      case '处理中':
        return 'in-progress'
      case '待测试':
        return 'pending'
      default:
        return 'pending'
    }
  },
  
  getPriorityClass(priority) {
    switch (priority) {
      case '紧急':
        return 'urgent'
      case '高':
        return 'high'
      case '中':
        return 'medium'
      case '低':
        return 'low'
      default:
        return 'medium'
    }
  },

  onProjectNameInput(e) {
    this.setData({
      'project.name': e.detail.value
    })
    // 调试信息
    console.log('项目名称输入:', e.detail.value);
  },

  onProjectDescriptionInput(e) {
    this.setData({
      'project.description': e.detail.value
    })
  },

  onSaveProject() {
    if (!this.data.project.name) {
      wx.showToast({
        title: '请输入项目名称',
        icon: 'none'
      })
      return
    }
    
    if (this.data.action === 'create') {
      // 创建项目
      const userInfo = wx.getStorageSync('userInfo') || {}
      const createdBy = userInfo.id
      
      if (!createdBy) {
        wx.showToast({
          title: '用户信息错误',
          icon: 'none'
        })
        return
      }
      
      post(apiPaths.createProject, {
        name: this.data.project.name,
        description: this.data.project.description,
        createdBy: createdBy
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '项目创建成功',
            icon: 'success'
          })
          
          // 返回项目列表页面
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.message || '项目创建失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '项目创建失败',
          icon: 'none'
        })
      })
    } else {
      // 更新项目
      post(apiPaths.updateProject, {
        id: this.data.projectId,
        name: this.data.project.name,
        description: this.data.project.description,
        status: this.data.project.status
      }).then(res => {
        if (res.code === 200) {
          wx.showToast({
            title: '项目更新成功',
            icon: 'success'
          })
          
          // 重新加载项目详情
          this.loadProjectDetail(this.data.projectId)
        } else {
          wx.showToast({
            title: res.message || '项目更新失败',
            icon: 'none'
          })
        }
      }).catch(err => {
        wx.showToast({
          title: err.message || '项目更新失败',
          icon: 'none'
        })
      })
    }
  },

  onCancel() {
    wx.navigateBack()
  },

  // 显示添加成员弹窗
  onAddMember() {
    this.setData({
      showAddMemberModal: true,
      selectedMember: null,
      memberRole: '成员'
    })
  },
  
  // 关闭添加成员弹窗
  onCloseAddMemberModal() {
    this.setData({
      showAddMemberModal: false
    })
  },
  
  // 选择成员
  onMemberSelect(e) {
    this.setData({
      selectedMember: e.detail.value
    })
  },
  
  // 角色输入
  onRoleInput(e) {
    this.setData({
      memberRole: e.detail.value
    })
  },
  
  // 确认添加成员
  onConfirmAddMember() {
    if (!this.data.selectedMember) {
      wx.showToast({
        title: '请选择成员',
        icon: 'none'
      })
      return
    }
    
    if (!this.data.projectId) {
      wx.showToast({
        title: '项目ID不能为空',
        icon: 'none'
      })
      return
    }
    
    post(apiPaths.addProjectMember, {
      projectId: this.data.projectId,
      userId: this.data.selectedMember,
      role: this.data.memberRole
    }).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: '成员添加成功',
          icon: 'success'
        })
        
        this.setData({
          showAddMemberModal: false
        })
        
        // 重新加载项目详情
        this.loadProjectDetail(this.data.projectId)
      } else {
        wx.showToast({
          title: res.message || '成员添加失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.message || '成员添加失败',
        icon: 'none'
      })
    })
  },

  onRemoveMember(e) {
    const memberId = e.currentTarget.dataset.id
    wx.showModal({
      title: '确认删除',
      content: '确定要移除该成员吗？',
      success: (res) => {
        if (res.confirm) {
          // 调用删除成员接口
          post(apiPaths.removeProjectMember, {
            projectId: this.data.projectId,
            userId: memberId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '已移除成员',
                icon: 'success'
              })
              // 重新加载项目详情
              this.loadProjectDetail(this.data.projectId)
            } else {
              wx.showToast({
                title: res.message || '移除成员失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '移除成员失败',
              icon: 'none'
            })
          })
        }
      }
    })
  },
  
  // 更新成员角色
  onUpdateMemberRole(e) {
    const memberId = e.currentTarget.dataset.id
    const member = this.data.project.members.find(m => m.id == memberId)
    
    if (member) {
      // 这里可以显示一个输入框让用户输入新的角色
      wx.showModal({
        title: '更新角色',
        editable: true,
        placeholderText: '请输入新角色',
        content: member.role,
        success: (res) => {
          if (res.confirm) {
            const newRole = res.content
            if (newRole) {
              post(apiPaths.updateProjectMemberRole, {
                projectId: this.data.projectId,
                userId: memberId,
                role: newRole
              }).then(res => {
                if (res.code === 200) {
                  wx.showToast({
                    title: '角色更新成功',
                    icon: 'success'
                  })
                  // 重新加载项目详情
                  this.loadProjectDetail(this.data.projectId)
                } else {
                  wx.showToast({
                    title: res.message || '角色更新失败',
                    icon: 'none'
                  })
                }
              }).catch(err => {
                wx.showToast({
                  title: err.message || '角色更新失败',
                  icon: 'none'
                })
              })
            }
          }
        }
      })
    }
  },

  onAddTask() {
    console.log('Adding task for project ID:', this.data.projectId);
    wx.navigateTo({
      url: '/pages/createTask/createTask?projectId=' + this.data.projectId
    })
  },

  onTaskTap(e) {
    const taskId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/taskDetail/taskDetail?id=${taskId}`
    })
  },

  onManageWorkflow() {
    wx.navigateTo({
      url: '/pages/workflow/workflow?projectId=' + this.data.projectId
    })
  },

  onOpenChat() {
    wx.showToast({
      title: '群聊功能开发中',
      icon: 'none'
    })
  },

  onEditProject() {
    wx.navigateTo({
      url: '/pages/projectDetail/projectDetail?id=' + this.data.projectId + '&action=edit'
    })
  },

  onDeleteProject() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除该项目吗？此操作不可恢复',
      success: (res) => {
        if (res.confirm) {
          // 调用删除项目接口
          post(apiPaths.deleteProject, {
            id: this.data.projectId
          }).then(res => {
            if (res.code === 200) {
              wx.showToast({
                title: '项目已删除',
                icon: 'success'
              })
              setTimeout(() => {
                wx.navigateBack()
              }, 1500)
            } else {
              wx.showToast({
                title: res.message || '项目删除失败',
                icon: 'none'
              })
            }
          }).catch(err => {
            wx.showToast({
              title: err.message || '项目删除失败',
              icon: 'none'
            })
          })
        }
      }
    })
  }
})